﻿using System;
using System.Data.SqlClient;
using System.Linq;
using System.Threading;
using Common.Logging;
using OutDbContext;
using Rmq.Center;
using User.Api.BizExtensions;
using User.Api.Helpers.WeixinPayV3.WxResult;
using User.Api.Helpers;

namespace Out.TaskRunner.RmqWorkers
{
    public class OrderPayingTimeoutWorker : IWorker
    {
        private static readonly ILog Logger = LogManager.GetLogger(typeof(OrderPayingTimeoutWorker));

        public void Start(CancellationToken ct)
        {
            if (ct.IsCancellationRequested)
            {
                return;
            }

            using (var consumer = new OrderPayingTimeoutConsumer())
            {
                consumer.Subscribe((id, count, dt, msg, channel) =>
                {
                    if (msg.OrderType == OrderType.挂号订单)
                    {
                        return ProcessRegOrder(msg.OrderId, channel);
                    }
                    else if (msg.OrderType == OrderType.门诊缴费订单)
                    {
                        //处理门诊缴费订单支付超时
                        return ProcessBillOrder(msg.OrderId, channel);
                    }
                    else if (msg.OrderType == OrderType.刷卡支付订单)
                    {
                        //处理门诊缴费订单支付超时
                        return ProcessMicroPayOrder(msg.OrderId, channel);
                    }

                    return new ConsumedResult { Ack = true };
                });

                while (true)
                {
                    if (ct.IsCancellationRequested)
                    {
                        break;
                    }

                    Thread.Sleep(50);
                }
            }
        }

        private ConsumedResult ProcessMicroPayOrder(int orderId, WrapperChannel channel)
        {
            using (var ctx = new HzfyWeiXinEntities())
            {
                var order = ctx.MicroPayOrder.IsStatus(MicroPayOrderExtensions.OrderStatus.支付中, MicroPayOrderExtensions.OrderStatus.支付失败)
                    .FirstOrDefault(x => x.Id == orderId);
                if (order != null)
                {
                    // 支付失败
                    order.OrderStatus = MicroPayOrderExtensions.OrderStatus.支付失败.ToInt32().ToString();
                    order.PayState = MicroPayOrderExtensions.PayState.未付款.ToInt32().ToString();
                    ctx.SaveChanges();
                    var orderPayReverseProducer = new OrderPayReverseProducer();
                    orderPayReverseProducer.Publish(new OrderPayReverseMsg
                    {
                        OrderType = OrderType.刷卡支付订单,
                        OrderId = order.Id
                    });
                }
                else
                {
                    order = ctx.MicroPayOrder.IsStatus(MicroPayOrderExtensions.OrderStatus.撤销成功)
                .FirstOrDefault(x => x.Id == orderId);
                    if (order != null)
                    {
                        var res = WeixinPayV3Helper.OrderQuery("MP" + order.OrderNo);
                        bool canReverse = false;
                        if (res.ResultCode == "0")
                        {

                            // 交易状态  trade_state  是  String(32) 
                            // SUCCESS—支付成功 
                            // REFUND—转入退款 
                            // NOTPAY—未支付 
                            // CLOSED—已关闭 
                            // REVOKED—已撤销（刷卡支付）
                            // USERPAYING--用户支付中 
                            // PAYERROR--支付失败(其他原因，如银行返回失败)
                            if (res.TradeState.ToUpper() == "SUCCESS")
                            {
                                canReverse = true;

                            }
                        }
                        if (canReverse)
                        {
                            // 支付失败
                            order.OrderStatus = MicroPayOrderExtensions.OrderStatus.支付失败.ToInt32().ToString();
                            order.PayState = MicroPayOrderExtensions.PayState.未付款.ToInt32().ToString();
                            ctx.SaveChanges();
                            var orderPayReverseProducer = new OrderPayReverseProducer();
                            orderPayReverseProducer.Publish(new OrderPayReverseMsg
                            {
                                OrderType = OrderType.刷卡支付订单,
                                OrderId = order.Id
                            });
                        }

                    }
                }


            }

            return new ConsumedResult
            {
                Ack = true
            };
        }

        private ConsumedResult ProcessRegOrder(int orderId, WrapperChannel channel)
        {
            OrderSummary order;
            using (var ctx = new HzfyWeiXinEntities())
            {
                order = ctx.ApptOrder.IsStatus(ApptOrderExtensions.OrderStatus.支付中)
                    .Where(x => x.Id == orderId).Select(x => new OrderSummary
                    {
                        OrderStatus = x.OrderStatus,
                        OrderType = x.OrderType,
                        Id = x.Id
                    }).FirstOrDefault();
                if (order == null)
                {
                    return new ConsumedResult
                    {
                        Ack = true
                    };
                }
                //暂不主动查询微信支付信息
                //var trid = GerWeixinPayInfo("AP" + order.OrderNo);
                //if (string.IsNullOrEmpty(trid))
                //{
                //    order.Remark = order.Remark??""+"||支付信息未保存订单：" + trid;
                //}
                // 支付失败
                //order.OrderStatus = ApptOrderExtensions.OrderStatus.支付失败.ToInt32();
                //ctx.SaveChanges();

                SqlParameter[] para =
                {
                    new SqlParameter("@OrderStatus", ApptOrderExtensions.OrderStatus.支付失败.ToInt32()),
                    new SqlParameter("@OrderId", orderId),
                };
                ctx.Database.ExecuteSqlCommand(
                    "Update ApptOrder set OrderStatus= @OrderStatus where Id=@OrderId", para);
            }

            if (order.OrderType == ApptOrderExtensions.OrderType.预约.ToInt32().ToString())
            {
                // RMQ 执行取消预约操作
                //var unapptingProducer = new OrderUnapptingProducer();
                //unapptingProducer.Publish(new OrderUnapptingMsg
                //{
                //    OrderType = Rmq.Center.OrderType.挂号订单,
                //    OrderId = order.Id
                //});

                // RMQ 执行取消锁号操作
                var unlockingProducer = new OrderUnlockingProducer();
                unlockingProducer.Publish(new OrderUnlockingMsg
                {
                    OrderType = OrderType.挂号订单,
                    OrderId = orderId
                });
            }


            return new ConsumedResult
            {
                Ack = true
            };
        }

        private ConsumedResult ProcessBillOrder(int orderId, WrapperChannel channel)
        {
            using (var ctx = new HzfyWeiXinEntities())
            {
                var order = ctx.BillOrder.IsStatus(BillOrderExtensions.OrderStatus.支付中)
                    .FirstOrDefault(x => x.Id == orderId);
                if (order == null)
                {
                    return new ConsumedResult
                    {
                        Ack = true
                    };
                }

                // 支付失败
                order.OrderStatus = BillOrderExtensions.OrderStatus.支付失败.ToInt32();
                ctx.SaveChanges();


            }

            return new ConsumedResult
            {
                Ack = true
            };
        }


        public class OrderSummary
        {
            public int OrderStatus { get; set; }
            public string OrderType { get; set; }
            public int Id { get; set; }
        }
    }
}